package org.jaychan.live.account.provider.rpc;

import jakarta.annotation.Resource;
import org.jaychan.live.account.interfaces.IAccountTokenService;
import org.jaychan.live.framework.redis.key.AccountProviderCacheKeyBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AccountTokenServiceImpl implements IAccountTokenService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private AccountProviderCacheKeyBuilder accountProviderCacheKeyBuilder;

    @Override
    public String createAndSaveLoginToken(Long userId) {
        String tokenKey = UUID.randomUUID().toString();
        String loginTokenKey = accountProviderCacheKeyBuilder.buildUserLoginTokenKey(tokenKey);
        redisTemplate.opsForValue().set(loginTokenKey, String.valueOf(userId), 30, TimeUnit.DAYS);
        return tokenKey;
    }

    @Override
    public Long getUserIdByToken(String tokenKey) {
        String loginTokenKey = accountProviderCacheKeyBuilder.buildUserLoginTokenKey(tokenKey);
        Integer userId = (Integer)redisTemplate.opsForValue().get(loginTokenKey);

        return userId == null? null : Long.valueOf(userId);
    }

}